if RFirst then
    RFirst = 1;
else
    RFirst = 2;
end

if RFirst == 2 then
    RCount = 1;
end

if RFirst == 1 then
    RCount = RCount + 1;
end

if RCount > 2 then
    RCount = 1;
end

switch RCount 
case 1
    require "import"
    import "android.content.Context"
    import "android.os.Vibrator"
    import "java.io.FileOutputStream"
    import "java.io.OutputStreamWriter"
    import "java.io.BufferedReader"
    import "java.io.InputStreamReader"
    import "android.media.MediaRecorder"
    import "android.media.MediaScannerConnection"
    import "java.io.File"
    import "java.io.FileInputStream"
    import "java.text.SimpleDateFormat"
    import "java.util.Date"
    import "android.content.ContentValues"
    import "android.provider.MediaStore"

    local folderPath = "/storage/emulated/0/التسجيلات"
    local folder = File(folderPath)

    if not folder.exists() then
        local success = folder.mkdirs()

        if success then
            service.asyncSpeak("تم إنشاء المجلد في المسار: " .. folderPath)
        else
            service.asyncSpeak("تعذر إنشاء المجلد في المسار: " .. folderPath)
        end
    end

    counterFile = File("/storage/emulated/0/orden.txt")
    counterFile.delete()

    local isRecording = false
    local folderName = "التسجيلات"
    local folderPath = "/storage/emulated/0/" .. folderName
    local counterFilePath = "/storage/emulated/0/contador.txt"
    local dateFormat = SimpleDateFormat("HH_mm_ss", Locale.getDefault())
    local currentTime = dateFormat.format(Date())
    local outputFile = folderPath .. "/recorded_audio_" .. currentTime .. ".wav"

    local function createCounterFile()
        local file = File(counterFilePath)
        if not file.exists() then
            file.createNewFile()
            local outputStream = FileOutputStream(file)
            local writer = OutputStreamWriter(outputStream)
            writer.write("1")
            writer.close()
            outputStream.close()
        end
    end

    local function readFileContent(file)
        local content = ""
        local bufferedReader = BufferedReader(InputStreamReader(FileInputStream(file)))
        local line = bufferedReader.readLine()
        while line do
            content = content .. line
            line = bufferedReader.readLine()
        end
        bufferedReader.close()
        return content
    end

    local function getCounter()
        createCounterFile()
        local file = File(counterFilePath)
        local content = readFileContent(file)
        local counter = tonumber(content)
        return counter
    end

    local function updateCounter(counter)
        local file = File(counterFilePath)
        local outputStream = FileOutputStream(file)
        local writer = OutputStreamWriter(outputStream)
        writer.write(tostring(counter))
        writer.close()
        outputStream.close()
    end

    local function getNextRecordingNumber()
        local counter = getCounter()
        updateCounter(counter + 1)
        return counter
    end

    function stopRecording()
        if isRecording then
            mediaRecorder.stop()
            mediaRecorder.release()
            mediaRecorder = nil
            isRecording = false

            MediaScannerConnection.scanFile(this, {outputFile}, nil, nil)

            local values = ContentValues()
            values.put(MediaStore.MediaColumns.DATA, outputFile)
            values.put(MediaStore.MediaColumns.TITLE, "تسجيل صوتي")
            values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/wav")
            this.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)
        end
    end

    local function startRecording()
        if not isRecording then
            mediaRecorder = MediaRecorder()
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC)
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS)
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
            mediaRecorder.setAudioEncodingBitRate(320000)
            mediaRecorder.setAudioSamplingRate(48000)
            
            local recordingNumber = getNextRecordingNumber()
            local recordingFile = File(folderPath, "audio_" .. recordingNumber .. ".wav")
            outputFile = recordingFile.getAbsolutePath()
            
            mediaRecorder.setOutputFile(outputFile)
            mediaRecorder.prepare()
            mediaRecorder.start()
            isRecording = true
        end
    end

    startRecording()

    local context = activity or service
    local vibrator = context.getSystemService(Context.VIBRATOR_SERVICE)
    if vibrator.hasVibrator() then
        vibrator.vibrate(100)
    end

    return true

case 2
    stopRecording()
    service.asyncSpeak("تم إنهاء التسجيل")

    require "import"
    import "android.content.Context"
    import "android.os.Vibrator"

    local context = activity or service
    local vibrator = context.getSystemService(Context.VIBRATOR_SERVICE)
    if vibrator.hasVibrator() then
        vibrator.vibrate(200)
    end

    return true
end

return true